const moment = require('moment')
const md5 = require('md5');
const jwt = require('jwt-simple')
const { Formidable } = require('formidable');
const path = require('path')
const fs = require('fs')
// 防破解加密key
const KEY = 'for(let i=0;i<10000;i++){console.log("iloveyou")}'

module.exports = {
    getNowTime:()=>{
        return moment().format('YYYY-MM-DD HH:mm:ss')
    },
    md5:(password)=>{
        return md5(password + KEY)
    },
    // 加密  {adminName:'atguigu'}
    encode:(payload,exp=60*60*24)=>{
        // 加入过期时间
        payload.exp = Date.now()/1000 + exp// {adminName:'atguigu',exp:xxxx}
        console.log('payload',payload)
        return jwt.encode(payload,KEY)
    },
    // 解密
    decode:(token)=>{
        // 1. 成功
        // 2. 失败
        return new Promise((resolve,reject)=>{
            // 解密失败会报错，所以用try-catch处理
            try{
                let payload = jwt.decode(token,KEY)
                resolve(payload)
            }catch(e){
                reject(e.message)
            }
        })
    },
    upload:(request, attr)=>{// attr  input type=file  name=[attr]
        console.log('upload')
        const form = new Formidable({
            uploadDir: path.resolve(__dirname, '../public/upload'),
            keepExtensions: true
        });
        return new Promise((resolve,reject)=>{
            form.parse(request, async (err, fields, files) => {
                if(err){
                    console.log('err')
                    reject(err)
                }
                let file = files[attr] //  input type=file  name=advPic
                if (file.size === 0) {
                    // 说明没有传文件，删除upload中的空文件==>fs模块
                    fs.unlinkSync(file.filepath)
                } else {
                    // 有文件上传
                    fields[attr] = file.newFilename
                }
                resolve(fields)
            })
        })
    }
}